import warnings
warnings.filterwarnings("ignore")
import numpy as np
from flask import Flask, request, jsonify
from keras.models import load_model
import pickle
import numpy as np
from gevent.pywsgi import WSGIServer


#加载scaler
with open('model/humidity_scaler.pk1', 'rb') as fr_humidity_scaler:
    scaler_humidity = pickle.load(fr_humidity_scaler)
with open('model/illumination_scaler.pk1', 'rb') as fr_illumination_scaler:
    scaler_illumination = pickle.load(fr_illumination_scaler)
with open('model/s_temperature_scaler.pk1', 'rb') as fr_s_temperature_scaler:
    scaler_s_temperature = pickle.load(fr_s_temperature_scaler)
with open('model/temperature_scaler.pk1', 'rb') as fr_temperature_scaler:
    scaler_temperature = pickle.load(fr_temperature_scaler)
scaler_mapper = {}
scaler_mapper['hum'] = scaler_humidity
scaler_mapper['ill'] = scaler_illumination
scaler_mapper['soil_tem'] = scaler_s_temperature
scaler_mapper['tem'] = scaler_temperature

#加载模型
model_humidity = load_model('model/humidity_model.h5')
model_illumination = load_model('model/illumination_model.h5')
model_s_temperature = load_model('model/s_temperature_model.h5')
model_temperature = load_model('model/temperature_model.h5')
model_mapper = {}
model_mapper['hum'] = model_humidity
model_mapper['ill'] = model_illumination
model_mapper['soil_tem'] = model_s_temperature
model_mapper['tem'] = model_temperature

app = Flask(__name__)

@app.route('/predict', methods={'get'})
def tsd_pred():
    data_type = request.args.get("data_type")

    if not(data_type in scaler_mapper.keys()):
        return jsonify({'data': None})

    scaler_select = scaler_mapper[data_type]
    model_select = model_mapper[data_type]

    data = request.args.get("src_data",type=str,default=None)
    humd_datas = eval(data)
    humd_datas = np.array(humd_datas)

    #清洗数据
    data_process = scaler_select.transform(humd_datas)
    data_process = data_process.reshape(humd_datas.shape[0], 1, humd_datas.shape[1])
    humd_pred = model_select.predict(data_process)
    humd_result = scaler_select.inverse_transform(humd_pred).reshape(humd_pred.shape[1], 1)
    humd_result = np.squeeze(humd_result)

    return jsonify({'data': str(humd_result)})


if __name__ == '__main__':
    WSGIServer(('0.0.0.0', 5000), app).serve_forever()